package models

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"new1/appconfig"
)

type New1 struct {
	gorm.Model
	Name    string `gorm:"type:varchar(20)" json:"name"`
	Title   string `gorm:"type:varchar(20)" json:"title"`
	Area    string `gorm:"type:varchar(20)" json:"area"`
	Address string `gorm:"type:varchar(20)" json:"address"`
}

var DB *gorm.DB

func Init() {
	var err error
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	MysqlData := appconfig.Config.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", MysqlData.User, MysqlData.Password, MysqlData.Host, MysqlData.Port, MysqlData.Database)
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	DB.AutoMigrate(&New1{})
}

func (c *New1) Add() error {
	return DB.Create(&c).Error
}
func (c *New1) Update() error {
	return DB.Updates(&c).Error
}
func (c *New1) Del() error {
	return DB.Delete(&c).Error
}
func (c *New1) List() (li []*New1, err error) {
	err = DB.Find(&c).Error
	return li, err
}
